package utils

import (
	"bytes"
	"fmt"
	"k8s-admin/global"
	"k8s-admin/models"
	"os/exec"
	"time"
)

type Ansible struct {
	Args       string
	Inventory  string
	ModuleName string
}

func NewAnsible(Args, Inventory, ModuleName string) *Ansible {
	return &Ansible{
		Args:       Args,
		Inventory:  Inventory,
		ModuleName: ModuleName,
	}
}

func (this *Ansible) RunAnsible(task_number string) (string, error) {
	var stdout bytes.Buffer
	var stderr bytes.Buffer
	fmt.Println("ansible", this.Inventory, "-m", this.ModuleName, "-a", this.Args)
	start := time.Now() // 开始执行时间
	cmd := exec.Command("ansible", this.Inventory, "-m", this.ModuleName, "-a",this.Args)
	cmd.Stdout = &stdout
	cmd.Stderr = &stderr
	err := cmd.Run()
	if err != nil {
		global.TPLogger.Error(err)
		return "", err
	} else {
		expend_time := time.Now().Sub(start)
		err = global.GORM.Model(&models.Task{}).Where("task_number", task_number).Updates(&models.Task{
			StartTime:  start.Format(time.DateTime),
			ExpendTime: expend_time.String(),
			Status:     1,
		}).Error
		if err != nil {
			global.TPLogger.Error(err)
		}
		return stdout.String(), nil
	}
}

// 剧本方法
// func (this *Ansible)RunPlaybook(){}

// cron 定时任务
